package com.iqiyi.pps.epg.core.rpc.carousel;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.pps.epg.api.model.web.carousel.*;
import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.server.web.carousel.CarouselWebService;
import com.iqiyi.pps.epg.core.model.carousel.*;
import com.iqiyi.pps.epg.core.model.channel.ChannelBase;
import com.iqiyi.pps.epg.core.service.carousel.CarouselService;
import com.iqiyi.pps.epg.core.service.carousel.ICarouselAsyncService;
import com.iqiyi.pps.epg.core.service.channel.ChannelService;
import com.iqiyi.pps.epg.core.utils.ApiLegoUtil;
import com.iqiyi.pps.epg.core.utils.ApplicationContextUtil;
import com.iqiyi.pps.epg.core.utils.Constants;
import com.iqiyi.pps.epg.core.utils.DateTimeUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lemuel on 2015/6/4.
 */
public class CarouselWebServiceImpl implements CarouselWebService.Iface {
    public static Logger logger = LoggerFactory.getLogger(CarouselWebServiceImpl.class);

    @Override
    public long create(TCarousel entity) throws TException {
        long result = 0;
        if (null != entity) {
            CarouselBase carouselBase = new CarouselBase();
            carouselBase.setFatherId(entity.getFatherId());
            carouselBase.setQipuId(entity.getQipuId());
            carouselBase.setShowName(entity.getShowName());
            if (StringUtils.isNotBlank(entity.getStartTime())) {
                carouselBase.setStartTime(Timestamp.valueOf(entity.getStartTime()));
            }
            if (StringUtils.isNotBlank(entity.getEndTime())) {
                carouselBase.setEndTime(Timestamp.valueOf(entity.getEndTime()));
            }
            carouselBase.setItemTime(entity.getItemTime());
            carouselBase.setStartNum(entity.getStartNum());
            carouselBase.setFollowNum(entity.getFollowNum());
            carouselBase.setTotalNum(entity.getTotalNum());
            carouselBase.setRepeatedStatus(entity.getRepeatedStatus());
            carouselBase.setFollowedStatus(entity.getFollowedStatus());
            carouselBase.setChannelTag(entity.getChannelTag());

            if ("-100".equals(entity.getCopyrightEndTime())) {
                carouselBase.setCopyrightEndTime(-100L);
            } else {
                carouselBase.setCopyrightEndTime(StringUtils.isBlank(entity.getCopyrightEndTime()) ? carouselBase.DEFAULT_COPYRIGHT_END_TIME :
                        DateTimeUtil.parseLongFormat(entity.getCopyrightEndTime()));
            }

            carouselBase.setBossStatus(entity.getBossStatus());
            carouselBase.setPublishStatus(entity.getPublishStatus());
            carouselBase.setCreatedTime(new Timestamp(System.currentTimeMillis()));
            carouselBase.setOpUser(entity.getOpUser());
            carouselBase.setActualNum(entity.getActualNum());
            carouselBase.setStatus(carouselBase.DEFAULT_STATUS);
            carouselBase.setPageUrl(null == entity.getPageUrl() ? StringUtils.EMPTY : entity.getPageUrl());

            String shortCreateStartTime = entity.getCreateStartTime().substring(0, 10);
            int gapDays = DateTimeUtil.getBetweenDays(DateTimeUtil.getCurrentDay(), shortCreateStartTime);

            carouselBase.setExtendTime(new Timestamp(DateTimeUtil.getPreviousDay(shortCreateStartTime).getTime()));

            carouselBase.setLastCreatedNo(carouselBase.DEFAULT_LAST_CREATED_NO);
            carouselBase.setLastCreatedQipuId(carouselBase.DEFAULT_LAST_CREATED_QIPUID);

            CarouselService service = (CarouselService) ApplicationContextUtil.getBean(CarouselService.class);

            // Check whether the carousel has existed.
            TFilter filter = new TFilter();
            Map<String, String> params = new HashMap<>();
            params.put("EQL_qipuId", String.valueOf(entity.getQipuId()));
            params.put("EQT_startTime", entity.getStartTime());
            params.put("EQI_followNum", String.valueOf(entity.getFollowNum()));
            params.put("EQI_repeatedStatus", String.valueOf(entity.getRepeatedStatus()));
            params.put("EQI_followedStatus", String.valueOf(entity.getFollowedStatus()));
            params.put("EQI_status", "1");
            filter.setFilters(params);
            TPage page = new TPage(-1, 1, 1, "id", "asc", false);

            TCarouselPage tempResult = carouselList(page, filter);

            if (tempResult.getResultSize() > 0) {
                return result;
            }

            // Create carousel rule.
            long start1 = System.currentTimeMillis();
            service.saveBase(carouselBase);
            long start2 = System.currentTimeMillis();
            logger.info("[CarouselWebServiceImpl][create][saveBase][time={}]", (start2 - start1));
            result = carouselBase.getId();

            if (result > 0 && gapDays <= service.getCarouselCreateDay()) {
                service.executeRules(carouselBase, entity.getCreateDays(), entity.getCreateStartTime());
                logger.info("[CarouselWebServiceImpl][create][executeRules]");
            }
        }
        return result;
    }

    @Override
    public boolean delCarousel(String ids) throws TException {
        CarouselService service = (CarouselService) ApplicationContextUtil.getBean(CarouselService.class);
        boolean delFlag = service.delCarousel(ids);
        return delFlag;
    }

    @Override
    public TCarouselPage getByFatherId(String fatherId) throws TException {
        TFilter filter = new TFilter();
        Map<String, String> params = new HashMap<>();
        params.put("father_id", fatherId);
        filter.setFilters(params);

        TPage page = new TPage(-1, 1, 10000, "id", "asc", true);

        return carouselList(page, filter);
    }

    @Override
    public TCarouselPage carouselList(TPage page, TFilter filter) throws TException {
        TCarouselPage result = null;

        CarouselService service = (CarouselService) ApplicationContextUtil.getBean(CarouselService.class);
        long start1 = System.currentTimeMillis();
        result = service.getList(page, filter);
        long start2 = System.currentTimeMillis();
        logger.info("[CarouselWebServiceImpl][carouselList][getCarouselList][time={}]", (start2 - start1));

        return result;
    }

    @Override
    public List<TCarouselAutomation> getCarouselAutomationList(long channelId) throws TException {
        CarouselService service = (CarouselService) ApplicationContextUtil.getBean(CarouselService.class);
        List<AutoCarouselEpisodeRule> list = service.getCarouselAutomationList(channelId);
        return service.transToTCarouselAutomationList(list);
    }

    @Override
    public TAutomationPage automationList(TPage page, TFilter filter) throws TException {
        TAutomationPage result = null;
        CarouselService service = (CarouselService) ApplicationContextUtil.getBean(CarouselService.class);
        long start1 = System.currentTimeMillis();
        result = service.getAutomationList(page, filter);
        long start2 = System.currentTimeMillis();
        logger.info("[CarouselWebServiceImpl][automationList][time={}]", (start2 - start1));
        return result;
    }

    @Override
    public TCarouselAutomation getByAutomationId(long entityId) throws TException {
        CarouselService service = (CarouselService) ApplicationContextUtil.getBean(CarouselService.class);
        AutoCarouselEpisodeRule rule = service.getByAutomationId(entityId);
        TCarouselAutomation tCarouselAutomation = service.transToTCarouselAutomation(rule);
        return tCarouselAutomation;
    }

    @Override
    public long createAutomation(TCarouselAutomation entity) throws TException {
        CarouselService service = (CarouselService) ApplicationContextUtil.getBean(CarouselService.class);
        List<AutoCarouselEpisodeRule> list = service.getCarouselAutomationList(entity.getFatherId());
        for (AutoCarouselEpisodeRule rule : list) {
            if (rule.getStatus() == 1) {
                logger.info("[createAutomation] automation running ; cid={}", entity.getFatherId());
                return -2;
            }
        }

        AutoCarouselEpisodeRule autoCarouselEpisodeRule = new AutoCarouselEpisodeRule();
        autoCarouselEpisodeRule.setFatherId(entity.getFatherId());
        autoCarouselEpisodeRule.setQipuId(entity.getQipuId());
        autoCarouselEpisodeRule.setShowName(entity.getShowName());
        autoCarouselEpisodeRule.setTotalNum(entity.getTotalNum());
        autoCarouselEpisodeRule.setChannelTag(entity.getChannelTag());
        autoCarouselEpisodeRule.setBossStatus(entity.getBossStatus());
        autoCarouselEpisodeRule.setPublishStatus(entity.getPublishStatus());
        autoCarouselEpisodeRule.setCreatedTime(new Timestamp(System.currentTimeMillis()));
        autoCarouselEpisodeRule.setOpUser(entity.getOpUser());
        autoCarouselEpisodeRule.setActualNum(entity.getActualNum());
        autoCarouselEpisodeRule.setStatus(AutoCarouselEpisodeRule.STATUS_IDLE);
        autoCarouselEpisodeRule.setPageUrl(null == entity.getPageUrl() ? StringUtils.EMPTY : entity.getPageUrl());
        autoCarouselEpisodeRule.setExecuteTime(new Timestamp(System.currentTimeMillis()));
        autoCarouselEpisodeRule.setExecIndex(System.currentTimeMillis());
        service.saveAutomation(autoCarouselEpisodeRule);
        return autoCarouselEpisodeRule.getId();
    }

    @Override
    public boolean delAutomation(String ids) throws TException {
        CarouselService service = (CarouselService) ApplicationContextUtil.getBean(CarouselService.class);
        boolean delFlag = service.delAutomation(ids);
        return delFlag;
    }

    @Override
    public int indexMoveAutomation(long id, long aimId) throws TException {
        CarouselService service = (CarouselService) ApplicationContextUtil.getBean(CarouselService.class);
        return service.indexMoveAutomation(id, aimId);
    }

    @Override
    public int indexMoveEpisode(long id, long aimId) throws TException {
        CarouselService service = (CarouselService) ApplicationContextUtil.getBean(CarouselService.class);
        return service.indexMoveEpisode(id, aimId);
    }

    @Override
    public int indexMoveAutomationByIndex(long id, int aimIndex) throws TException {
        CarouselService service = (CarouselService) ApplicationContextUtil.getBean(CarouselService.class);
        return service.indexMoveAutomationByIndex(id, aimIndex);
    }

    @Override
    public int indexMoveEpisodeByIndex(long id, int aimIndex) throws TException {
        CarouselService service = (CarouselService) ApplicationContextUtil.getBean(CarouselService.class);
        return service.indexMoveEpisodeByIndex(id, aimIndex);
    }

    @Override
    public int changeAutomationStatus(long channelId, int execStatus) throws TException {
        //  CarouselService service = (CarouselService) ApplicationContextUtil.getBean(CarouselService.class);
        ICarouselAsyncService service = (ICarouselAsyncService) ApplicationContextUtil.getBean(ICarouselAsyncService.class);
        //  return service.changeAutomationStatus(channelId,execStatus);
        return service.changeAutomationTask(channelId, execStatus);
    }

    @Override
    public String batchAddEpisode(List<Long> list, long fatherId,String opUser) throws TException {
        logger.info("[batchAddEpisode] start ,fatherId={},opUser={}",fatherId,opUser);
        JSONObject object = new JSONObject();
        try {
            if (list.size() == 0){
                object.put("ret", Constants.CODE_SUC);
                object.put("ret_msg",Constants.getCode(Constants.CODE_SUC));
                return object.toJSONString();
            }
            ChannelService channelService = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);
            ChannelBase channelBase = channelService.getChannelBase(fatherId);
            if (Integer.valueOf(3).compareTo(channelBase.getLiveType()) != 0) {
                object.put("ret", Constants.CODE_ERROR);
                object.put("ret_msg","频道不是轮播台");
                return object.toJSONString();
            }

            CarouselService service = (CarouselService) ApplicationContextUtil.getBean(CarouselService.class);
            if(service.isLibraryRuleRunning(fatherId)){
                object.put("ret", Constants.CODE_ERROR);
                object.put("ret_msg","请先停止规则");
                return object.toJSONString();
            }
            List<AutoCarouselEpisodeLibrary> pList = null;
            long checkQupuId = list.get(0);
            int rest = (int) (checkQupuId - checkQupuId / 100 * 100);
            AutoCarouselEpisodeLibrary original = null;
            if (rest == 0) {
                List<Long> hasIds = service.queryHasQipuIds(fatherId, list);
                hasIds.retainAll(list );
                if(hasIds.size() > 0){
                    object.put("multi", JSON.toJSONString(hasIds));
                }
                list.removeAll(hasIds );
                if( list.size() == 0){
                    object.put("ret",Constants.CODE_SUC);
                    object.put("ret_msg","没有有效数据");
                    return object.toJSONString();
                }
                List<ProgramLegoData> qipuDatas =  ApiLegoUtil.queryByQipuIds(list);
                pList = new ArrayList<>();
                for (ProgramLegoData temp : qipuDatas) {
                    original = temp.getOriginal();
                    original.setFatherId( fatherId);
                    original.setOpUser(opUser);
                    pList.add(original);
                }
                object.put("ret",Constants.CODE_SUC);
                object.put("ret_msg",Constants.getCode(Constants.CODE_SUC));
                service.saveAutoProgramDataList(pList,fatherId );
               // service.save
            } else if (rest == 23) {
                object.put("ret",Constants.CODE_ERROR);
                object.put("ret_msg","not support ");
                return object.toJSONString();
            } else {
                logger.warn("no such rest qipuId " + rest);
                object.put("ret",Constants.CODE_ERROR);
                object.put("ret_msg","no such rest qipuId " + rest);
                return object.toJSONString();
            }
            logger.info("[batchAddEpisode]");
        } catch (Exception e) {
            logger.error("[batchAdd][fatherId=" + fatherId + "][exception:{}]", e);
            object.put("ret",Constants.CODE_ERROR);
            object.put("ret_msg","出现异常");
        }
        logger.info("[batchAddEpisode] end ,fatherId={},opUser={}",fatherId,opUser);
        return object.toJSONString();
    }

    @Override
    public String batchDelEpisode(List<Long> idList, long channelId) throws TException {
        JSONObject object = new JSONObject();
        if(idList.size() == 0){
            object.put("ret",Constants.CODE_SUC);
            object.put("ret_msg",Constants.getCode(Constants.CODE_SUC));
            return object.toJSONString();
        }
        CarouselService service = (CarouselService) ApplicationContextUtil.getBean(CarouselService.class);

        if( service.isLibraryRuleRunning( channelId )){
            object.put("ret",Constants.CODE_ERROR);
            object.put("ret_msg","规则正在执行中不能删除");
            return object.toJSONString();
        }
        boolean delFlag = service.delCarouselEpisode( idList.toString().replaceAll("\\[|\\]|\\s",""));
        if(delFlag){
            object.put("ret",Constants.CODE_SUC);
            object.put("ret_msg",Constants.getCode(Constants.CODE_SUC));
        }else{
            object.put("ret",Constants.CODE_ERROR);
            object.put("ret_msg","删除失败");
        }
        return object.toJSONString();
    }

    @Override
    public TCarouselEpisodePage carouselEpisodeList(TPage page, TFilter filter) throws TException {
        TCarouselEpisodePage result = null;
        CarouselService service = (CarouselService) ApplicationContextUtil.getBean(CarouselService.class);
        long start1 = System.currentTimeMillis();
        result = service.getCarouselEpisodeList(page, filter);
        long start2 = System.currentTimeMillis();
        logger.info("[CarouselWebServiceImpl][carouselEpisodeList][time={}]", (start2 - start1));
        return result;
    }
}
